﻿using System;
using System.Collections;
using System.Linq;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace ZhukBlogSharePointProject.CustomEntityPicker
{
    public class CustomEntityEditorWithPicker : EntityEditorWithPicker
    {
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            PickerDialogType = typeof(CustomPickerDialog);
            MultiSelect = CustomProperty == "1";
            var ctx = SPContext.Current;
            SiteId = ctx.Site.ID;
            WebId = ctx.Web.ID;
            Height = new Unit(100, UnitType.Percentage);
            CssClass = "ms-usereditor";
            CheckButtonImageName = "/_layouts/images/CHECK2.gif";
            BrowseButtonImageName = "/_layouts/images/RTE2FIND.gif";
        }

        private Guid SiteId { get; set; }
        private Guid WebId { get; set; }

        public override PickerEntity ValidateEntity(PickerEntity entity)
        {
            if (entity == null) return null;
            if (entity.IsResolved)
            {
                return entity;
            }
            SPSecurity.RunWithElevatedPrivileges(
                () =>
                {
                    var hrData = new FakeDataRepository();
                    var emps = hrData.GetObjects(entity.DisplayText);
                    if (emps.Count() == 1)
                    {
                        entity = emps.First().ToPickerEntity();
                        entity.IsResolved = true;
                    }
                    else
                    {
                        entity.IsResolved = false;
                    }
                });
            return entity;
        }

        protected override PickerEntity[] ResolveErrorBySearch(string unresolvedText)
        {
            var res = new PickerEntity[] { };
            SPSecurity.RunWithElevatedPrivileges(
                () =>
                {
                    var hrData = new FakeDataRepository();
                    var emps = hrData.GetObjects(unresolvedText);
                    res = emps.Select(e => e.ToPickerEntity()).ToArray();
                });
            return res;
        }

        public override string DialogTitle
        {
            get
            {
                return "Поиск объектов";
            }
            set
            {
                base.DialogTitle = value;
            }
        }

        public new void UpdateEntities(ArrayList list)
        {
            base.UpdateEntities(list);
        }
    }
}
